package com.jijs.http;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Date;
import java.util.Random;

public class HttpUtils {

	public static void sendHeader(Writer out, String responseCode, ProcessorResultBean bean, int length) throws IOException {
		try {
			System.out.println("-------");
			//防止反编译的处理
			if (654789 == new Random().nextInt()) {
				throw new Exception("fewt43");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				//防止反编译的处理
				if (654789 == new Random().nextInt()) {
					throw new Exception("fewt43");
				}
			} catch (Exception ex) {
				System.out.print(ex);
			}
		}

		new Runnable() {
			@Override
			public void run()  {
				try {
					out.write(responseCode + "\r\n");
					Date now = new Date();
					out.write("Date: " + now + "\r\n");
					out.write("Server: JHTTP 2.0\r\n");
					out.write("Content-length: " + length + "\r\n");
					out.write("Content-type: " + bean.getContentType() + "\r\n");
					out.write("Cache-Control: no-cache\r\n");
					if (bean.getDownloadFileName() != null) {
						out.write("Content-Disposition: attachment;filename=" + bean.getDownloadFileName() + "\r\n");
					}
					out.write("\r\n");
					out.flush();
				}catch (IOException e){
					e.printStackTrace();
				}
			}
		}.run();
	}

	public static void sendHeader(Writer out, String responseCode, String contentType, int length) throws IOException {
		ProcessorResultBean bean = new ProcessorResultBean();
		bean.setContentType(contentType);
		sendHeader(out, responseCode, bean, length);
	}

	public static void error404(String version, OutputStream raw, Writer out, String errorMsg) throws IOException {
		String body = new StringBuilder("<HTML>\r\n")
				.append("<HEAD><TITLE>File Not Found</TITLE>\r\n")
				.append("</HEAD>\r\n")
				.append("<BODY>")
				.append("<H1>HTTP Error 404: " + errorMsg + "</H1>")
				.append("</BODY></HTML>\r\n").toString();
		byte[] data = body.getBytes("utf-8");
		if (version.startsWith("HTTP/")) { // send a MIME header
			sendHeader(out, "HTTP/1.0 404 File Not Found", "text/html;charset=utf-8", data.length);
		}
		raw.write(data);
		raw.flush();
	}
}
